//previous page id, current page id
var prevPid = '', curPid = '';
//save opened frame name
var frameArr = [];
var uid = null;
var _int = null;

//frame whether open
function isOpened(frmName){
    var i = 0, len = frameArr.length;
    var mark = false;
    for(i; i<len; i++){
        if(frameArr[i] === frmName){
            mark = true;
            return mark;
        }
    }
    return mark;
}

//toggle header
function showHeader(type){
    if(!type){return;}
    var header = $api.dom('#header .active');
    
    $api.removeCls(header,'active');
    var thisHeader = $api.dom('#header .'+type);
    $api.addCls(thisHeader,'active');
}

//open tab
/*function openTab(type,tid){
    
    if(type === 'user'){
    	//login
	    var uid = $api.getStorage('uid');
		if(!uid){
			api.openWin({
		        name: 'userLogin',
		        url: './html/userLogin.html',
		        opaque: true,
		        vScrollBarEnabled:false
		    });
		    return;
		}
    }
    
    showHeader(type);
    var width = api.winWidth;
    var nav = $api.byId('nav');
    var navPos = $api.offset(nav);
    var header = $api.byId('header');
    var headerPos = $api.offset(header);
    var height = api.winHeight - navPos.h - headerPos.h;
    
    type = type || 'main';

    var actTab = $api.dom('#nav .active');
    $api.removeCls(actTab,'active');
    var thisTab = $api.dom('#nav .'+ type);
    thisTab = thisTab.parentNode;
    $api.addCls(thisTab,'active');

    //record page id
    prevPid = curPid;
    curPid = type;
    
    if(prevPid !== curPid){

        // alert(type+':'+isOpened(type));
    
        if(isOpened(type)){

            api.setFrameAttr({
                name: type,
                hidden: false
            });
        }else{
            api.openFrame({
                name: type,
                url: 'html/'+ type +'.html',
                bounces: true,
                opaque: true,
                vScrollBarEnabled: false,
                pageParam:{ headerHeight: headerPos.h,tid:tid},
                rect: {
                    x: 0,
                    y: headerPos.h,
                    w: width,
                    h: height
                }
            });
        }

        if(prevPid){
            api.setFrameAttr({
                name: prevPid,
                hidden: true
            });
            
        }

        if(!isOpened(type)){
            //save frame name
            frameArr.push(type);
        }
        
    }
    
}*/

function openFrameGroup(frames) {
   
    var width = api.winWidth;
    var nav = $api.byId('nav');
    var navPos = $api.offset(nav);
    var header = $api.byId('header');
    var headerPos = $api.offset(header);
    //alert(headerPos.h)
    var height = api.winHeight - navPos.h - headerPos.h;
  
   $api.setStorage('height',''+height);
        api.openFrameGroup({
            name: 'group',
            scrollEnabled: true,
            rect: {
                    x: 0,
                    y: headerPos.h,
                    w: width,
                    h: height
                },
            
            preload:4,
            frames: frames
        }, function (ret, err) {
          
           var type = ret['name'];
           var index = ret['index']
        /*   if(index==4){
            api.setFrameGroupAttr({
                 name: 'group',
                rect: {
                    x: 0,
                    y: 0,
                    w: width,
                    h: height
                }
        });
           }else{
            api.setFrameGroupAttr({
            name: 'group',
            rect: {
                    x: 0,
                    y: headerPos.h,
                    w: width,
                    h: height
                }
            });
           }*/
         

           if(index==3){
             api.execScript({
                                    name:'root',
                                    frameName: 'cart',
                                    script: 'getCart(true)'
                                });
           }
           if(index==4){
             api.execScript({
                                    name:'root',
                                    frameName: 'user',
                                    script: 'userReload()'
                                });
           }
                showHeader(ret['name']);
                 var actTab = $api.dom('#nav .act');
    $api.removeCls(actTab,'act');
    var thisTab = $api.dom('#nav .'+ type);
    
    thisTab = thisTab.parentNode;
    $api.addCls(thisTab,'act');
            
        });
    }

function changeCityTab(str){
    if(str){
        var title = $api.dom('#header .activity .city span');
        $api.text(title, str);
    }
}
function exec(){

openFrame(3);

}
function exec2(){
_openFrame(0);

}

function changeTypeTab(str){
    if(str){
        var title = $api.dom('#header .activity .hot span');
        $api.text(title, str);
    }
}
//search activity
var searchActOpened = false;

function closeFramGroup(){
    api.closeFrameGroup({
        name: 'searchAct'
    });

    var actLi = $api.dom('#header .activity li.active');
    $api.removeCls(actLi,'active');
    searchActOpened = false;
}

//search activity
function searchAct(el,type){
    if(!el || !type){return;}

    var header = $api.byId('header');
    var pos = $api.offset(header);

    var index = 0;  //frame group index
    if(type === "type"){
        index = 1;
    }

    if(!searchActOpened){
        api.openFrameGroup ({
            name: 'searchAct',
            scrollEnabled: false,
            rect:{x: 0, y: pos.h, w: 'auto', h: 'auto'},
            index: index,
            preload: 0,
            frames:[{
                name: 'searchActBy-city',
                url: 'html/searchActBy-city.html',
                bounces: false,
                opaque: false,
                bgColor: 'rgba(51,51,51,0.6)',
                vScrollBarEnabled: false
            },{
                name: 'searchActBy-type',
                url: 'html/searchActBy-type.html',
                bounces: false,
                opaque: false,
                bgColor: 'rgba(51,51,51,0.6)',
                vScrollBarEnabled:false
            }]
        }, function(ret, err){
            
        });

        searchActOpened = true;
    }else{
        api.setFrameGroupIndex ({
            name: 'searchAct',
            index: index
            // ,scroll: true
        });
        api.setFrameGroupAttr({
            name: 'searchAct',
            hidden: false
        });
    }

    //toggle active style
    var curLi = el.parentNode;
    //close frame group
    if($api.hasCls(curLi,'active')){
        
        api.setFrameGroupAttr({
            name: 'searchAct',
            hidden: true
        });
        
    }
    $api.toggleCls(curLi,'active');

    var lis = $api.domAll('#header .activity li');
    var i = 0, len = lis.length;

    for(i; i<len; i++){
        var thisLi = lis[i];
        if(thisLi === curLi){
            continue;
        }else{
            if($api.hasCls(thisLi,'active')){
                $api.removeCls(thisLi,'active');
            }
        }
    }

}

function setting(){
    api.openWin({
        name: 'setting',
        url: 'html/setting.html',
        opaque: true,
        delaye:200,
        vScrollBarEnabled:false
    });
}

function filterNews(type){
	var nav = $api.dom('#header .news .submenu');
	var actNav = $api.dom(nav, '.light');
	$api.removeCls(actNav, 'light');
	$api.addCls(event.target, 'light');
	var id='548ec1f272c60e937d21c8cf';

	switch (type){
		case 'hot':
			api.execScript({
				frameName: 'news',
	            script: 'initPage(\''+id+'\');'
            });
			break;
		case 'local':
			api.execScript({
				frameName: 'news',
	            script: 'initPage(\''+id+'\');'
            });
			break;
		case 'topic':
			api.execScript({
				frameName: 'news',
	            script: 'initPage(\''+id+'\');'
            });
			break;
	}
}

function scan(){
	var obj = api.require('scanner');
	obj.open(function(ret,err) {
		var resUrl = ret.msg;
		if(!resUrl){return;}
		
	    api.openApp({
	        iosUrl: resUrl,
	        androidPkg: 'android.intent.action.VIEW',
	        mimeType: 'text/html',
	        uri: resUrl
	    }, function (ret, err) {
			
	    });
	    
	});
}
function changeNum(){

        var cartNum = $api.getStorage("cartNum");
        var cartNumtxt = $api.byId('cartNum');
       
        if(cartNum){

             if(cartNum!=0){
                $api.css(cartNumtxt,'display:block')
                $api.html(cartNumtxt,cartNum);
             }else{
                $api.css(cartNumtxt,'display:none')
                $api.html(cartNumtxt,cartNum);
             }      
        }
    }
//推送
function _push(){
	var push = new ajPush();
	if (api.systemType == "android") {
		push.action();
		push.getRegistrationId();
		push.addEventListener();
		push.setListener();
	}else{
		push.getRegistrationId();
		push.addEventListener();
		push.setListener();
	}    
	    push.setBadge();
	    push.clearNotification();
	//push.onResume();	
}
function _meiqia(){
	//创建美洽
var mq = api.require('meiQia');
//配置初始化美洽需要的appkey
var param = {
    appkey: "996240d57ac05390f86687c094d8aade"
};
//初始化美洽
mq.initMeiQia(param, function(ret, err) {
    if (ret) {
        //初始化成功
    } 
})
}

apiready = function(frames){
_push();
_meiqia();
//  绑定用户
/*var push = api.require('push');
push.bind({
    userName:'testName',
    userId:'testId'
},function(ret,err){
    if(ret.status){
        //api.alert({msg:'绑定成功'});
    }else{
        api.alert({msg:err.msg});
    }
});
push.setListener(
    function(ret,err){
        if(ret){
            //api.alert({msg:ret.data});
        }
    }
);*/

checkUpdate()
//talkingData
/*var td = api.require('talkingData');
td.getDeviceID(function(ret, err) {
    if (ret) {
        //api.alert({ msg: ret });
    }
});
*/
//云修复监听
api.addEventListener({
    name:'smartupdatefinish'
}, function(ret, err){
	if(ret){
		api.rebootApp();
	}     
    
});
var mKeyTime;
api.addEventListener({
            name : 'keyback'
    }, function() {
            if (mKeyTime != undefined) {
                    if ((new Date().getTime() - mKeyTime) < 2000) {
                              api.closeWidget({
						    id: 'A6904857437572',
						    retData: {
						        name: 'closeWidget'
						    },
						    silent:true,
						    animation: {
						        type: 'flip',
						        subType: 'from_bottom',
						        duration: 500
						    }
						});
                    }else{
                    	 api.toast({
                    msg : '再按一次退出机器猫',
                    duration : 2000,
                    location : 'bottom'
            });
                    }
            }else{
            api.toast({
                    msg : '再按一次退出机器猫',
                    duration : 2000,
                    location : 'bottom'
            });
            }
           
            mKeyTime = new Date().getTime();
    });



api.addEventListener({
    name: 'myread'
}, function(ret, err) {
    if(ret.value['read']=='Y'){
    	$api.css($api.byId('message_icon'),'display:none');
    }
});
	
	headerstatus()

	api.setStatusBarStyle({
    style: 'light'
   	});

	api.setFrameAttr({
            name: api.winName,
          
            bounces:false
        });
 	var winHeight = $(this).height();
 
 	$api.setStorage('winHeight',winHeight);
	window.onresize = function(){
 	var width = api.winWidth;
    var nav = $api.byId('nav');
    var navPos = $api.offset(nav);
    var header = $api.byId('header');
    var headerPos = $api.offset(header);
   	var height1 = winHeight - (headerPos.h+4);

   	var height2 = winHeight - navPos.h - headerPos.h;
   	var _height = $(this).height();
   	

   	
	if($api.getStorage('height')==height2){
		var height = height1;	
	}else{
		var height = height2;
	}
	if(winHeight>_height){	
   		var height = height2-(headerPos.h+4); 		
   	}
   
   	
    $api.setStorage('height',height)
	api.setFrameGroupAttr({
    name: 'group',
    rect: {
                    x: 0,
                    y: headerPos.h,
                    w: width,
                    h: height
                },
});
} 
 
    changeNum();
   
   
    var header = $api.byId('header');
    //$api.fixIos7Bar(header);

    //status bar style
    
    api.setFullScreen({
    	fullScreen: false
	});
  
    //判断用户是否登录
    if($api.getStorage('user')){
    	uid = $api.getStorage('user').uid;
    }
    
    //监听账号是否切换
    api.addEventListener({
    	name: 'user'
	}, function(ret, err) {
		if(uid!=ret.value.uid){
			uid = ret.value.uid;
		    clearInterval(_int)
		    _int = setInterval(m,1000)//发送推送
		}
	      
	});
	api.addEventListener({
    name:'resume'
}, function(ret, err){  

	if(uid!=null){
		//r();
	}
    
});
    if(uid){
    // r();
		_int = setInterval(m,1000)//发送推送
    	
    	
    }
    function r(){
    	var params = { account: ""+uid };
			
    }
      
    function m(){
   
    /*揭晓通知状态*/
    api.ajax({
	        url:'http://wap.jqmao.cn/getLottMessage?uid='+uid+'&type='+api.systemType,
        },function(ret,err){
        	//coding...
        	if(ret){
            	if(ret.read=='N'){
            		$api.css($api.byId('message_icon'),'display:block');
            	}
        	}else{
        		//alert(JSON.stringify(err));
        	}
        });
    }
    
    
    
   var str='';

    var aa = [{
        name: 'main', 
        url: 'html/main.html',
        bgColor: '#fff',
        bounces:true,
        customRefreshHeader: 'UIPullRefresh'
    },{
        name: 'lottery', 
        url: 'html/lottery.html', 
        bgColor: '#fff',
        bounces:true,
        customRefreshHeader: 'UIPullRefresh',
        

    },{
        name: 'activity', 
        url: 'html/activity.html', 
        bgColor: '#fff',
        bounces:false,
        

    },{
        name: 'cart', 
        url: 'html/cart.html', 
        bgColor: '#fff',
        bounces:true,
        customRefreshHeader: 'UIPullRefresh'
       
    },{
        name: 'user', 
        url: 'html/user.html', 
        bgColor: '#fff',
        bounces:false,
     
    }]
  
        

    openFrameGroup(aa)
    //openTab('main','548ec1e708d4718e7d771bbe');
};




